package org.scau.weibo.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.scau.weibo.services.IBlogService;
import org.scau.weibo.util.NameClassAndMethod;
import org.scau.weibo.vo.BComment;
import org.scau.weibo.vo.BMessage;
import org.scau.weibo.vo.BUser;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BlogAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private BMessage blog;
	private BComment comment;
	private IBlogService blogService;
	private String result;
	private File image;//接收的图�?
	private String imageFileName;//图片名称必须写，否则接收不成�?
	private String imageContentType;//图片类型必须写，否则接收不成�?
	private String message="成功";//json字符串，返回到上传页�?

	@Override
	public String execute() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		return null;
	}

	//列出所有微博
	public String listBlogs() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		
		List<Map<String,Object>> blogs=new ArrayList<Map<String,Object>>();
		List<BMessage> list=new ArrayList<BMessage>();
		Map<String, Object> session=ActionContext.getContext().getSession();
		BUser user=(BUser)session.get("user");
/*		if(user!=null){
			list = this.blogService.selectAttentionBlogAll(user.getUserId());
		}
		else{
			list=this.blogService.selectBlogAll();
		}*/
		list=this.blogService.selectBlogAll();
		for (int i = 0; i < list.size(); i++) {
			this.blogService.getCurrentSession().beginTransaction();
			blogs.add(list.get(i).toMap());
			this.blogService.getCurrentSession().close();
		}
		
		if(blogs!=null){
			JSONArray jsonArray = JSONArray.fromObject(blogs); 
//			JSONObject json = JSONObject.fromObject(map);
			setResult(jsonArray.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}
	
	//搜索
		public String search() throws Exception {
			NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
			HttpServletRequest request =  ServletActionContext.getRequest();
			request.setCharacterEncoding("UTF-8"); 
			List<Map<String,Object>> blogs=new ArrayList<Map<String,Object>>();
			List<BMessage> list=new ArrayList<BMessage>();
			System.out.println(request.getParameter("k"));
			list=this.blogService.search(request.getParameter("k"));
			for (int i = 0; i < list.size(); i++) {
				blogs.add(list.get(i).toMap());
			}
			if(blogs!=null){
				JSONArray jsonArray = JSONArray.fromObject(blogs); 
				setResult(jsonArray.toString());
				System.out.println(this.result);
			}
			return SUCCESS;
		}

	//列出用户关注所有微博
	public String listAttentionBlogs() throws Exception {
		// TODO 可能有问题
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		List<BMessage> blogs = this.blogService.selectAttentionBlogAll(user.getUserId());
		if(blogs!=null){
			map.put("blogs", blogs);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//发微博
	public String sendBlog() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		HttpServletRequest request =  ServletActionContext.getRequest();
		Map<String, Object> map=new HashMap<String, Object>();
		request.setCharacterEncoding("UTF-8"); 
		String realpath = ServletActionContext.getServletContext().getRealPath("/images");
		String content=new String(blog.getMessageContent().getBytes("iso-8859-1"),"utf-8");//乱码解决
		blog.setMessageContent(content);
		BUser user=(BUser)session.get("user");
		System.out.println(user);
		if(user!=null){
			if (image != null) {
				String timeStr="ph"+System.currentTimeMillis();  
		        String suffix = getImageFileName().substring(getImageFileName().lastIndexOf("."));//获取后缀
				String name=timeStr+suffix;//上传后的文件名
		        File savefile= new File(realpath+File.separator+name);
				if (!savefile.getParentFile().exists())
					savefile.getParentFile().mkdirs();
				try {
					Date date=new Date(); 
					FileUtils.copyFile(image, savefile);
					System.out.println(name);
					blog.setMessageLink(name);
					blog.setBUser(user);
					blog.setMessageDate(date);
					System.out.println(date);
					this.blogService.addBlog(blog);
					System.out.println(blog);
					map.put("success", true);
					map.put("url", name);
				} catch (IOException e) {
					message="上传失败";
					e.printStackTrace();
				}
			}
			else if(blog!=null){
				Date date=new Date(); 
				blog.setBUser(user);
				blog.setMessageDate(date);
				this.blogService.addBlog(blog);
				System.out.println(blog);
				map.put("success", true);
			}
			
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//转发微博
	public String forwardBlog() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			this.blogService.forward(user, blog.getMessageId());
//			this.blogService.addForwardCount(blog.getMessageForwardId(), 1);
		}
		return SUCCESS;
	}

	
	
	//收藏微博
	public String collectBlog() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null&&blog!=null){
			Date date=new Date(); 
			this.blogService.insertCollect(user.getUserId(), blog.getMessageId(), date);;
			this.blogService.addCollectCount(blog.getMessageId(), 1);
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//取消收藏
	public String cancelCollectBlog() throws Exception {
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null&&blog!=null){
			this.blogService.deleteCollect(user.getUserId(), blog.getMessageId());
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试

		return SUCCESS;
	}

	//评论微博
	public String commentBlog() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			Date date=new Date(); 
			comment.setBUser(user);
			comment.setMessageDate(date);
			comment.setBMessage(blog);
			this.blogService.insertComment(comment);
			this.blogService.addReviewCount(blog.getMessageId(), 1);
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//回复评论
	public String replayCommentBlog() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			Date date=new Date(); 
			comment.setCommentedUserId(user.getUserId());;
			comment.setMessageDate(date);
			comment.setBMessage(blog);
			this.blogService.insertComment(comment);
			this.blogService.addReviewCount(blog.getMessageId(), 1);
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//查看@我的消息
	public String showUserRelateBlogInfo() throws Exception {
		// TODO Auto-generated method stub 未完整。待解决分页问题
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			this.blogService.selectRelateBlogAll(user.getUserName(), 0, 1);
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//删除评论
	public String deleteCommentBlogInfo() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			this.blogService.deleteComment(comment.getCommentId());
			map.put("success", true);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//查看评论
	public String showBlogCommentInfo() throws Exception {
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			List<BComment> comments=this.blogService.queryComment(blog.getMessageId());
			map.put("comments", comments);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//查看原创微博
	public String showBlogOriginalInfo() throws Exception {
		// TODO 没实现分页显示功能
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			List<BMessage> blogs=this.blogService.selectOriginalBlogAll();
			map.put("blogs", blogs);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	//查看图片微博
	public String showBlogPictureInfo() throws Exception {
		// TODO 没实现分页功能
		NameClassAndMethod.name();//返回当前的类名和方法名，方便调试
		Map<String, Object> session=ActionContext.getContext().getSession();
		Map<String, Object> map=new HashMap<String, Object>();
		BUser user=(BUser)session.get("user");
		if(user!=null){
			List<BMessage> blogs=this.blogService.selectPictureBlogAll();
			map.put("blogs", blogs);
			JSONObject json = JSONObject.fromObject(map);
			setResult(json.toString());
			System.out.println(this.result);
		}
		return SUCCESS;
	}

	public BMessage getBlog() {
		return blog;
	}

	public void setBlog(BMessage blog) {
		this.blog = blog;
	}

	public IBlogService getBlogService() {
		return blogService;
	}

	public BComment getComment() {
		return comment;
	}

	public void setComment(BComment comment) {
		this.comment = comment;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public void setBlogService(IBlogService blogService) {
		this.blogService = blogService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}
